<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\SystemConfig\Action\Admin;

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\AdminUser\Middleware\AdminAuthMiddleware;
use MoChat\Plugin\AdminUser\Middleware\PermissionMiddleware;
use MoChat\Plugin\SystemConfig\Contract\SystemConfigContract;

/**
 * 系统管理-列表
 * Class Index.
 * @Controller
 */
class Set extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var SystemConfigContract
     */
    protected $systemConfigService;

    /**
     * @Inject
     * @var StdoutLoggerInterface
     */
    protected $logger;

    /**
     * @Middlewares({
     *     @Middleware(AdminAuthMiddleware::class),
     *     @Middleware(PermissionMiddleware::class)
     * })
     * @RequestMapping(path="/admin/systemConfig/set", methods="POST")
     * @throws \JsonException
     */
    public function handle(): array
    {
        $user = user();

        // 接收参数
        $param = $this->request->all();
        // 验证参数
        $this->validated($param);

        foreach ($param as $item) {
            $info = $this->systemConfigService->getSystemConfigByName($item['configName'], ['id']);
            if (! empty($info)) {
                $data = [
                    'type' => 1,
                    'config_id' => $info['id'],
                    'value' => $item['configValue'],
                    'description' => $item['description'] ?? '',
                    'created_at' => date('Y-m-d H:i:s'),
                ];
                $this->systemConfigService->createSystemConfigValue($data);
            }
        }
        return [];
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
        ];
    }
}
